package cn.gok;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author: LKSV
 * @Description:
 * @Date:Created in 19:55 2021/8/22
 */
public class UserServiceImpl implements IUserService{
    @Override
    public String sayHello(String word) {
        System.out.println("调用成功===参数：" + word);
        return "调用成功===参数：" + word;
    }


    public static void startServer(String hostName, int port) {
        try {

            //创建线程实例
            NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            //创建服务端辅助启动类
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(eventLoopGroup)
                    //指定通道类型为NIO类型
                    .channel(NioServerSocketChannel.class)
                    //通道初始化
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();

                            //添加String类型的编解码器
                            p.addLast(new StringDecoder());
                            p.addLast(new StringEncoder());

                            //添加自定义的Handler处理器
                            p.addLast(new UserServerHandler());
                        }
                    });
            bootstrap.bind(hostName, port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
